###########################################################################
# Lipps & Sczepanski & Malet
# Understanding Preferences over Borders
# International Studies Quaterly

# Appendix: Additional analysis of the conjoint --------------------------
###########################################################################

rm(list = ls())

packages <- c("tidyverse", "cregg", "tidytext", "ggplot2", "xtable")

for (package in packages) {
  if (!requireNamespace(package, quietly = TRUE)) {
    install.packages(package, dependencies = TRUE)
  }
}

library(tidyverse)
library(ggplot2)
library(cregg)
library(xtable)
library(viridis)
library(ggpubr)

#Load data
dat_long <- read.csv("survey_dat_clean_conjoint.csv", na.strings=c("","NA"), row.names = 1)
dat <- read.csv("survey_dat_clean.csv", na.strings=c("","NA"), row.names = 1)

#recode
dat_long$border <- as.factor(dat_long$border)
dat_long$country <- as.factor(dat_long$country)
dat_long$aim <- as.factor(dat_long$aim)
dat_long$gender <- as.factor(dat_long$gender)
dat_long$migration_background <- as.factor(dat_long$migration_background)
dat_long$rati <- as.numeric(dat_long$rati)
dat_long$chosen <- as.factor(as.character(dat_long$chosen))

#make labels for plots
labels<- as_labeller(c("border" = "Measure", "aim"="Aim", "country"="Country", "sim_cat" = "Country"))

#### TABLES AND FIGURES ####--------------------------------------------------------

# Figure C1: Rating of chosen vs. not chosen proposals
pdf(file = "fig_C1.pdf",width = 8,height = 5,onefile=F)

ggplot(dat_long, aes(x=rati, color=chosen, fill=chosen)) + 
  geom_histogram(alpha=.7, position="dodge", bins=10, binwidth = 1) + 
  scale_x_continuous(breaks=c(0,1,2,3,4,5,6,7,8,9,10)) +
  scale_color_manual(values=c("red3", "deepskyblue3")) +
  scale_fill_manual(labels=c("0", "1"), values=c("red3", "deepskyblue3"), name="Choice") +
  guides(color = FALSE) + 
  labs(x="Rating of proposals", y="Frequency") +
  theme_bw() +
  theme(
    axis.text.y = element_text(size = 12),
    axis.text.x = element_text(size=12),
    axis.title.y= element_text(size = 14),
    axis.title.x = element_text(size=14),
    legend.position = "top",
    legend.text = element_text(size=12),
    legend.title = element_text(size=12))

dev.off()

#Figure C2: Rating by answer to openness question
dat_long$open_cat <- ordered(dat_long$open_cat, levels=c("open", "restricted", "closed"))

mu <- dat_long %>% group_by(open_cat) %>% summarise(mean=mean(rati, na.rm=T))

pdf(file = "fig_C2.pdf",width = 8,height = 5,onefile=F)

ggplot(dat_long, aes(x=rati, fill=open_cat)) +
  geom_histogram(aes(y = after_stat(count/sum(count))), alpha=.7, position = "dodge", bins=10, binwidth=1) +
  geom_vline(data=mu, aes(xintercept=mean, color=open_cat), size=1.4, linetype="dashed") +
  scale_x_continuous(breaks=c(0,1,2,3,4,5,6,7,8,9,10)) +
  scale_fill_manual(breaks=c("open", "restricted", "closed"), values=c("deepskyblue3", "darkgoldenrod1", "red3"), name="")+
  scale_color_manual(values=c("deepskyblue3", "darkgoldenrod1", "red3")) +
  labs(x="Rating of proposals", y="Percentage of proposals (each respondent rates 4x2)") +
  scale_y_continuous(labels= scales::percent) +
  guides(color=F) +
  theme_bw() +
  theme(
    axis.text.y.left = element_text(size = 12),
    axis.text.x = element_text(size=12),
    legend.text = element_text(size= 14),
    axis.title.y= element_text(size = 14),
    axis.title.x = element_text(size=14),
    legend.position = "top")

dev.off()

#Figure C3: Results - Forced choice
dat_long$chosen <- as.numeric(as.character(dat_long$chosen))
results_choice_main <- cregg::cj(chosen ~ border+aim+country, data=dat_long,
                                 id=~id, estimate="mm", h0=0.5)

pdf(file = "fig_C3.pdf",width = 8,height = 5,onefile=F)

ggplot(results_choice_main)+
  geom_point(aes(x=estimate, y=level), size=1.5)+
  geom_errorbar(aes(xmin=lower, xmax=upper, y=level), width=0, linewidth=1)+
  facet_grid(feature~., scales = "free", labeller = labels)+
  geom_vline(xintercept = 0.5, linetype="dotted")+
  labs(x="Marginal Means", y="")+
  theme_minimal() +
  theme(
    axis.text.y.left = element_text(size = 16),
    axis.text.x = element_text(size=16),
    axis.title.y= element_text(size = 16),
    axis.title.x = element_text(size=16),
    strip.text.y.right = element_text(size=16))

dev.off()

#Figure C4: by gender
results_gender<- cregg::cj(chosen ~ border+aim+country, data=dat_long,
                           id=~id, estimate="mm", h0=0.5, by=~gender)

pdf(file = "fig_C4.pdf",width = 8,height = 5,onefile=F)

ggplot(results_gender)+
  geom_point(aes(x=estimate, y=level, color=gender), size=2, position = position_dodge(0.4))+
  geom_errorbar(aes(xmin=lower, xmax=upper, y=level, color=gender), width=0, linewidth=1, position = position_dodge(0.4))+
  facet_grid(feature~., scales = "free", labeller = labels)+
  geom_vline(xintercept = 0.5, linetype="dotted")+
  labs(x="Marginal Mean", y="", color="")+
  scale_color_manual(values=c("deepskyblue3", "darkgoldenrod1"), labels=c("male", "female"))+
  theme_minimal() +
  theme(
    axis.text.y.left = element_text(size = 16),
    axis.text.x = element_text(size=16),
    axis.title.y= element_text(size = 16),
    axis.title.x = element_text(size=16),
    strip.text.y.right = element_text(size=16),
    legend.text = element_text(size=16))

dev.off()

#Figure C5: by migration background
results_migr<- cregg::cj(chosen ~ border+aim+country, data=dat_long,
                         id=~id, estimate="mm", h0=0.5, by=~migration_background)

pdf(file = "fig_C5.pdf",width = 8,height = 5,onefile=F)

ggplot(results_migr)+
  geom_point(aes(x=estimate, y=level, color=migration_background), size=2, position = position_dodge(0.4))+
  geom_errorbar(aes(xmin=lower, xmax=upper, y=level, color=migration_background), width=0, linewidth=1, position = position_dodge(0.4))+
  facet_grid(feature~., scales = "free", labeller = labels)+
  geom_vline(xintercept = 0.5, linetype="dotted")+
  labs(x="Marginal Mean", y="", color="Migration \nbackground")+
  scale_color_manual(values=c("deepskyblue3", "darkgoldenrod1"),labels=c("no", "yes"))+
  theme_minimal() +
  theme(
    axis.text.y.left = element_text(size = 16),
    axis.text.x = element_text(size=16),
    axis.title.y= element_text(size = 16),
    axis.title.x = element_text(size=16),
    strip.text.y.right = element_text(size=16),
    legend.text = element_text(size=16),
    legend.title = element_text(size=16))

dev.off()

#Figure C6: by national identity
dat_long %>% left_join(dat[,c("id", "identity_1", "identity_2")], by="id") %>%
  mutate(identity_cat = as.factor(case_when(identity_1 >=6 & identity_2 >= 6 ~ "Germany & Europe",
                                  identity_1>=6 & identity_2 <=4 ~ "Germany",
                                  identity_1 <=4 & identity_2 >= 6 ~ "Europe",
                                  TRUE ~ "neither"))) -> dat_long

result_ident <- cj(dat_long, chosen ~ border+aim+country, id=~id, estimate="mm", by=~identity_cat)

result_ident2 <- cj(dat_long, rati ~ border+aim+country, id=~id, estimate="mm", by=~identity_cat)

result_ident <- rbind(result_ident, result_ident2)

result_ident$identity_cat <- ordered(result_ident$identity_cat, levels=c("Europe", "Germany & Europe", "Germany", "neither"))

facets=as_labeller(c("chosen"="Forced choice", "rati"="Rating"))

pdf(file = "fig_C6.pdf",width = 8,height = 5,onefile=F)

ggplot(result_ident)+
  geom_point(aes(x=estimate, y=level, color=identity_cat), size=2, position = position_dodge(0.4))+
  geom_errorbar(aes(xmin=lower, xmax=upper, y=level, color=identity_cat), width=0, linewidth=1, position = position_dodge(0.4))+
  facet_grid(feature~., scales = "free", labeller = labels)+
  labs(x="Marginal Mean", y="")+
  scale_color_manual(values=c("#440154", "#3b528b", "#5ec962", "#fde725"), name="Identity")+
  theme_bw() +
  theme(
    axis.text.y.left = element_text(size = 12),
    axis.text.x = element_text(size=12),
    axis.title.y= element_text(size = 12),
    axis.title.x = element_text(size=12),
    strip.text.x = element_text(size=12),
    legend.text = element_text(size=12),
    legend.title = element_text(size=12),
    legend.position = "top") +
  facet_wrap(~outcome, scales = "free_x", labeller=facets)

dev.off()

#Figure C7: Interaction of border and aim with country
result_int1 <- cj(dat_long, chosen ~ border+aim, id = ~id, estimate = "mm", by = ~country)

pdf(file = "fig_C7.pdf",width = 8,height = 5,onefile=F)

ggplot(result_int1, aes(color=feature))+
  geom_point(aes(x=estimate, y=level), size=1.5)+
  geom_errorbar(aes(xmin=lower, xmax=upper, y=level), width=0, linewidth=1)+
  facet_grid(feature~., scales = "free", labeller = labels)+
  geom_vline(xintercept = 0.5, linetype="dotted")+
  labs(x="Marginal Means", y="")+
  scale_color_manual(values=c("deepskyblue3", "darkgoldenrod1")) +
  guides(color=FALSE) +
  theme_minimal() +
  theme(
    axis.text.y.left = element_text(size = 12),
    axis.text.x = element_text(size=12),
    axis.title.y= element_text(size = 12),
    axis.title.x = element_text(size=12),
    strip.text.y.right = element_text(size=12)) +
  facet_wrap(~BY, ncol = 2L)

dev.off()

#interaction of aim and country with border
#result_int2 <- cj(dat_long, chosen ~ aim+country, id = ~id, estimate = "mm", by = ~border)

#pdf(file = "fig_C3.pdf",width = 8,height = 5,onefile=F)

#ggplot(result_int2, aes(color=feature))+
#  geom_point(aes(x=estimate, y=level), size=1.5)+
#  geom_errorbar(aes(xmin=lower, xmax=upper, y=level), width=0, linewidth=1)+
#  facet_grid(feature~., scales = "free", labeller = labels)+
#  geom_vline(xintercept = 0.5, linetype="dotted")+
#  labs(x="Marginal Means", y="")+
#  scale_color_manual(values=c("deepskyblue3", "darkgoldenrod1")) +
#  guides(color=FALSE) +
#  theme_minimal() +
#  theme(
#    axis.text.y.left = element_text(size = 12),
#    axis.text.x = element_text(size=12),
#    axis.title.y= element_text(size = 12),
#    axis.title.x = element_text(size=12),
#    strip.text.y.right = element_text(size=12)) +
#  facet_wrap(~BY, ncol = 2L)

#dev.off()


#Figure C8: Most and least favored packages - pooled sample
dat_long <- dat_long %>% 
  mutate(combo = paste(border, aim, country, sep= ", "))

favorite_packages <- dat_long %>% 
  group_by(combo) %>% 
  summarise(mean_all = mean(rati, na.rm=TRUE), 
            sd_all = sd(rati, na.rm=TRUE), 
            n = n()) %>% 
  mutate(con_upper = mean_all +qt(1 - (0.05 / 2), n - 1)*(sd_all/sqrt(n)),
         con_lower = mean_all - qt(1 - (0.05 / 2), n - 1)*(sd_all/sqrt(n)))

top_packages <- favorite_packages %>%  
  slice_max(mean_all, n=3) %>% 
  mutate(rating = "highest")

worst_packages <- favorite_packages %>%  
  slice_min(mean_all, n=3)%>% 
  mutate(rating = "lowest")

max_packages <- rbind(top_packages, worst_packages)

pdf(file = "fig_C8.pdf",width = 8,height = 5,onefile=F)

ggplot(max_packages)+
  geom_bar(aes(x = reorder(combo, -mean_all), y=mean_all, fill = rating, color=rating), stat = "identity")+
  geom_errorbar(aes(x = reorder(combo, -mean_all), ymin=con_lower, ymax=con_upper), position=position_dodge(.9), width=.3, linewidth=1)+
  theme_minimal()+
  scale_color_manual(values=c("deepskyblue3", "darkgoldenrod1"))+
  scale_fill_manual(values=c("deepskyblue3", "darkgoldenrod1"))+
  labs(x="", y="Mean rating", color="Rating", fill = "Rating")+
  ylim(0,10)+
  coord_flip() +
  theme_minimal() +
  theme(
    axis.text.y = element_text(size = 12),
    axis.text.x = element_text(size=12),
    axis.title.x = element_text(size=16),
    legend.text = element_text(size=16),
    legend.title = element_text(size = 16))

dev.off()

#Figure C9: Most and least favorite packages of AfD and green voters
favorite_packages_party <- dat_long %>% 
  group_by(combo, vote_intention) %>% 
  summarise(mean_all = mean(rati, na.rm=TRUE), 
            sd_all = sd(rati, na.rm=TRUE), 
            n = n()) %>% 
  mutate(con_upper = mean_all +qt(1 - (0.05 / 2), n - 1)*(sd_all/sqrt(n)),
         con_lower = mean_all - qt(1 - (0.05 / 2), n - 1)*(sd_all/sqrt(n)))

top_packages_party <- favorite_packages_party %>%  
  group_by(vote_intention) %>% 
  slice_max(mean_all, n=3)%>% 
  mutate(rating = "highest")

worst_packages_party <- favorite_packages_party %>%  
  group_by(vote_intention) %>% 
  slice_min(mean_all, n=3)%>% 
  mutate(rating = "lowest")

max_packages_party<- rbind(top_packages_party, worst_packages_party)

afd_packages <- max_packages_party %>% 
  filter(vote_intention=="AfD") %>% 
  ggplot(.)+
  geom_bar(aes(x = reorder(combo, -mean_all), y=mean_all, color=rating, fill = rating), stat = "identity")+
  geom_errorbar(aes(x = reorder(combo, -mean_all), ymin=con_lower, ymax=con_upper), position=position_dodge(.9), width=.3, linewidth=1)+
  scale_color_manual(values=c("#3b528b", "deepskyblue3"))+
  scale_fill_manual(values=c("#3b528b", "deepskyblue3"))+
  theme_minimal()+
  ylim(0,10)+
  labs(x="", y="Mean rating", color="Rating", fill = "Rating", title="AfD supporters")+
  coord_flip() +
  theme_minimal() +
  theme(
    axis.text.y = element_text(size = 12),
    axis.text.x = element_text(size=12),
    axis.title.y= element_text(size = 16),
    axis.title.x = element_text(size=16),
    legend.text = element_text(size=16),
    legend.title = element_text(size = 16))

green_packages <- max_packages_party %>% 
  filter(vote_intention=="Greens") %>% 
  ggplot(.)+
  geom_bar(aes(x = reorder(combo, -mean_all), y=mean_all, color=rating, fill = rating), stat = "identity")+
  geom_errorbar(aes(x = reorder(combo, -mean_all), ymin=con_lower, ymax=con_upper), position=position_dodge(.9), width=.3, linewidth=1)+
  scale_color_manual(values=c("forestgreen", "#5ec962"))+
  scale_fill_manual(values=c("forestgreen", "#5ec962"))+
  theme_minimal()+
  ylim(0,10)+
  labs(x="", y="Mean rating", color="Rating", fill = "Rating", title="Green supporters")+
  coord_flip() +
  theme_minimal() +
  theme(
    axis.text.y = element_text(size = 12),
    axis.text.x = element_text(size=12),
    axis.title.y= element_text(size = 16),
    axis.title.x = element_text(size=16),
    legend.text = element_text(size=16),
    legend.title = element_text(size = 16))

pdf(file = "fig_C9.pdf",width = 8,height = 5,onefile=F)
ggarrange(green_packages, afd_packages, nrow=2)
dev.off()
